package ch3;

import util.Debug;

import java.util.Map;

/**
 * 在启动工作者线程时实现对象安全发布的示例
 */

public class SafeObjectPublishWhenStartingThread {
    private final Map<String, String> objectState;

    private SafeObjectPublishWhenStartingThread(Map<String, String> objectState) {
        this.objectState = objectState;
        // 不要在构造器中启动工作者线程，避免this逸出
    }

    private void init() {
        // 创建并启动工作者线程
        new Thread() {
            @Override
            public void run() {
               // 访问外层类实例的状态变量
               String value = objectState.get("someKey");
               Debug.info(value);
               // 省略其他代码
            }
        }.start();
    }

    // 工厂方法
    public static SafeObjectPublishWhenStartingThread newInstance(Map<String, String> objState) {
        SafeObjectPublishWhenStartingThread instance = new SafeObjectPublishWhenStartingThread(objState);
        instance.init();
        return instance;
    }
}
